<template>
  <div class="user-interest-tags">
    <div class="tags-header">
      <h3>{{ title || '选择您感兴趣的内容标签' }}</h3>
      <p class="tags-subtitle">{{ subtitle || '选择的标签将帮助我们为您推荐更符合您兴趣的内容' }}</p>
    </div>
    
    <div class="tags-selection">
      <!-- 当前已选择的标签 -->
      <div v-if="selectedTags.length > 0" class="selected-tags">
        <span class="section-label">已选择 ({{ selectedTags.length }}{{ maxSelections ? `/${maxSelections}` : '' }})：</span>
        <div class="tag-list">
          <span 
            v-for="tag in selectedTags" 
            :key="`selected-${tag}`"
            class="tag selected-tag"
          >
            {{ tag }}
            <span class="remove-tag" @click="removeTag(tag)">&times;</span>
          </span>
        </div>
      </div>
      
      <!-- 推荐标签区域 -->
      <div class="recommended-tags">
        <span class="section-label">推荐标签：</span>
        <div class="tag-list">
          <span 
            v-for="tag in recommendedTags" 
            :key="`recommended-${tag}`"
            class="tag recommended-tag"
            :class="{ 'selected': selectedTags.includes(tag) }"
            @click="toggleTag(tag)"
          >
            {{ tag }}
          </span>
        </div>
      </div>
      
      <!-- 热门标签区域 -->
      <div class="popular-tags" v-if="popularTags.length > 0">
        <span class="section-label">热门标签：</span>
        <div class="tag-list">
          <span 
            v-for="tag in popularTags" 
            :key="`popular-${tag}`"
            class="tag popular-tag"
            :class="{ 'selected': selectedTags.includes(tag) }"
            @click="toggleTag(tag)"
          >
            {{ tag }}
          </span>
        </div>
      </div>
    </div>
    
    <div class="tags-actions" v-if="showActions">
      <button 
        class="btn btn-secondary" 
        @click="clearAll" 
        :disabled="selectedTags.length === 0"
      >
        清空选择
      </button>
      <button 
        class="btn btn-primary" 
        @click="confirmSelection" 
        :disabled="!canConfirm"
      >
        {{ confirmText || '确认选择' }}
      </button>
    </div>
    
    <!-- 提示信息 -->
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    
    <div v-if="successMessage" class="success-message">
      {{ successMessage }}
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { getRecommendedInterestTags, updateUserInterests } from '../services/ageRecommendationService';

export default {
  name: 'UserInterestTags',
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    userId: {
      type: String,
      required: false
    },
    title: {
      type: String,
      default: '选择您感兴趣的内容标签'
    },
    subtitle: {
      type: String,
      default: '选择的标签将帮助我们为您推荐更符合您兴趣的内容'
    },
    maxSelections: {
      type: Number,
      default: 10
    },
    minSelections: {
      type: Number,
      default: 0
    },
    showActions: {
      type: Boolean,
      default: true
    },
    confirmText: {
      type: String,
      default: '确认选择'
    },
    autoSave: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'confirm', 'save', 'cancel'],
  setup(props, { emit }) {
    const selectedTags = ref([...props.modelValue]);
    const errorMessage = ref('');
    const successMessage = ref('');
    
    // 预设热门标签
    const popularTags = ref([
      '动漫', '电影', '音乐', '游戏', '科技', '知识',
      '美食', '旅行', '生活', '健身', '宠物', '时尚',
      '教育', '娱乐', '搞笑', '体育', '艺术', '汽车',
      '军事', '历史', '纪录片', '舞蹈', '手工', '摄影',
      '财经', '健康', '心理', '职场', 'Vlog', '开箱'
    ]);
    
    // 推荐标签计算
    const recommendedTags = ref([]);
    
    // 检查是否可以确认
    const canConfirm = computed(() => {
      return selectedTags.value.length >= props.minSelections;
    });
    
    // 切换标签选择状态
    const toggleTag = (tag) => {
      const index = selectedTags.value.indexOf(tag);
      
      if (index > -1) {
        // 移除标签
        removeTag(tag);
      } else {
        // 添加标签，检查是否超过最大限制
        if (props.maxSelections && selectedTags.value.length >= props.maxSelections) {
          errorMessage.value = `最多只能选择${props.maxSelections}个标签`;
          setTimeout(() => {
            errorMessage.value = '';
          }, 3000);
          return;
        }
        
        selectedTags.value.push(tag);
        if (props.autoSave) {
          saveSelections();
        }
      }
    };
    
    // 移除标签
    const removeTag = (tag) => {
      const index = selectedTags.value.indexOf(tag);
      if (index > -1) {
        selectedTags.value.splice(index, 1);
        if (props.autoSave) {
          saveSelections();
        }
      }
    };
    
    // 清空所有选择
    const clearAll = () => {
      selectedTags.value = [];
      if (props.autoSave) {
        saveSelections();
      }
    };
    
    // 确认选择
    const confirmSelection = () => {
      if (!canConfirm.value) {
        errorMessage.value = `请至少选择${props.minSelections}个标签`;
        setTimeout(() => {
          errorMessage.value = '';
        }, 3000);
        return;
      }
      
      emit('update:modelValue', [...selectedTags.value]);
      emit('confirm', [...selectedTags.value]);
      
      if (props.userId) {
        saveSelections();
      }
    };
    
    // 保存选择到用户数据
    const saveSelections = async () => {
      if (!props.userId) return;
      
      try {
        const result = updateUserInterests(props.userId, selectedTags.value);
        if (result) {
          successMessage.value = '标签更新成功！';
          emit('save', [...selectedTags.value]);
        } else {
          throw new Error('保存失败');
        }
      } catch (error) {
        errorMessage.value = '标签保存失败，请稍后重试';
        console.error('保存用户兴趣标签失败:', error);
      }
      
      // 清除提示信息
      setTimeout(() => {
        successMessage.value = '';
        errorMessage.value = '';
      }, 3000);
    };
    
    // 监听外部传入的modelValue变化
    watch(() => props.modelValue, (newValue) => {
      selectedTags.value = [...newValue];
    });
    
    onMounted(() => {
      // 生成推荐标签
      recommendedTags.value = getRecommendedInterestTags(selectedTags.value, popularTags.value);
    });
    
    return {
      selectedTags,
      popularTags,
      recommendedTags,
      errorMessage,
      successMessage,
      canConfirm,
      toggleTag,
      removeTag,
      clearAll,
      confirmSelection,
      saveSelections
    };
  }
};
</script>

<style scoped>
.user-interest-tags {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  margin: 0 auto;
}

.tags-header {
  margin-bottom: 24px;
  text-align: center;
}

.tags-header h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.tags-subtitle {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.tags-selection {
  margin-bottom: 24px;
}

.section-label {
  display: block;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.selected-tags {
  margin-bottom: 20px;
}

.selected-tags .section-label {
  color: #42b983;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 16px;
}

.tag {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.selected-tag {
  background-color: #42b983;
  color: white;
  border: 1px solid #42b983;
}

.selected-tag:hover {
  background-color: #3aa876;
  transform: translateY(-1px);
}

.remove-tag {
  font-size: 18px;
  line-height: 1;
  cursor: pointer;
  margin-left: 4px;
  padding: 0 2px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  transition: all 0.2s;
}

.remove-tag:hover {
  background: rgba(255, 255, 255, 0.3);
}

.recommended-tag {
  background-color: #f0f4f8;
  color: #333;
  border: 1px solid #d9e2ec;
}

.recommended-tag:hover {
  background-color: #e2e8f0;
  transform: translateY(-1px);
}

.recommended-tag.selected {
  background-color: #4299e1;
  color: white;
  border-color: #4299e1;
}

.popular-tag {
  background-color: #fff5f5;
  color: #e53e3e;
  border: 1px solid #fed7d7;
}

.popular-tag:hover {
  background-color: #fed7d7;
  transform: translateY(-1px);
}

.popular-tag.selected {
  background-color: #e53e3e;
  color: white;
  border-color: #e53e3e;
}

.tags-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
}

.btn {
  padding: 10px 24px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  outline: none;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #42b983;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #3aa876;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(66, 185, 131, 0.3);
}

.btn-secondary {
  background-color: #f0f4f8;
  color: #4a5568;
  border: 1px solid #d9e2ec;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #e2e8f0;
  transform: translateY(-1px);
}

.error-message,
.success-message {
  margin-top: 16px;
  padding: 12px 16px;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.error-message {
  background-color: #fed7d7;
  color: #c53030;
  border: 1px solid #feb2b2;
}

.success-message {
  background-color: #c6f6d5;
  color: #22543d;
  border: 1px solid #9ae6b4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-interest-tags {
    padding: 16px;
  }
  
  .tag {
    padding: 6px 12px;
    font-size: 13px;
  }
  
  .tags-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>